package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 *	8116
 * http://www.zaobao.com	联合早报
 *
 * @author KK
 *
 */
public class ZaobaoNewsAnalyse implements AnalyseNews {

	private static final String[] regex={
		/*
		*		[0-9]*
		*       [a-z]*
		*		[a-z0-9]*
		*       [a-zA-Z0-9]*
		*/

		"http://.*.zaobao.com/[a-zA-Z0-9]*/[a-zA-Z0-9]*/[a-z0-9]*/[a-z0-9\\-]*/story[0-9]*-[0-9]*",
		"http://.*.zaobao.com/[a-zA-Z0-9]*/[a-zA-Z0-9]*/[a-z0-9\\-]*/story[0-9]*-[0-9]*",
		"http://.*.zaobao.com/[a-zA-Z0-9]*/[a-z0-9\\-]*/story[0-9]*-[0-9]*",
		"http://.*.zaobao.com/[a-zA-Z0-9]*/story[0-9]*-[0-9]*",
		"http://.*.zaobao.com/.*/[a-z]*[0-9]{6,}[a-z]?.shtml",
	};

	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();
		String title=null;
		String content=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		news.setUrl(url);

		if(StringUtils.isBlank(title)) title =doc.select("title").text();
		if (title!=null){
			title=title.replace("www.zaobao.com", "");
			title=title.replace("|", "");
		}
		if(StringUtils.isBlank(content)) content=HtmlCleaner.getContentHtml(url,doc.select("td.text p"));
		if(StringUtils.isBlank(content)) content=HtmlCleaner.getContentHtml(url,doc.select("div#article_content,div#ap_content"));
		if(date==null) date=DateUtils.matchDate(doc.select("div#a_credit").text());
		if(date==null) date=DateUtils.matchDate(doc.select("p.cont").text());
		if (date==null){
			date=DateUtils.matchDate(url);
		}

		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setDate(date);
		news.setType(1);
		return news;
	}
	public static void main(String[] args) {
		String url="http://changzhou.zaobao.com/pages2/changzhou141011c.shtml";
		ZaobaoNewsAnalyse analyse=new ZaobaoNewsAnalyse();
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
